package com.atguigu.gmall.payment.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.enums.model.PaymentStatus;
import com.atguigu.gmall.enums.model.PaymentType;
import com.atguigu.gmall.payment.model.PaymentInfo;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@SuppressWarnings("all")
public class PaymentReceiver {

    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private AlipayService alipayService;

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_CLOSE,durable = "true"),
            value = @Queue(value = MqConst.QUEUE_PAYMENT_CLOSE,durable = "true"),
            key = MqConst.ROUTING_PAYMENT_CLOSE
    ))

    public void processPayClose(Long orderId, Channel channel, Message message){
        try {
            if(orderId != null){
                log.info("[支付服务]监听到关闭交易记录消息:{}",orderId);
                //1.根据订单id查询本地交易记录
               PaymentInfo paymentInfo = paymentInfoService.getPaymentInfoByOrderId(orderId,PaymentType.ALIPAY.name());
               //2.判断本地交易记录状态.如果未支付,    改为:关闭
                if(paymentInfo != null && PaymentStatus.UNPAID.name().equals(paymentInfo.getPaymentStatus())){
                    paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
                    paymentInfoService.updateById(paymentInfo);

                    //3.查询支付宝端交易状态,若是等待支付,直接关闭支付宝交易记录
                    String status = alipayService.getZhiFuBaoTradeStatus(paymentInfo.getTradeNo(), paymentInfo.getOutTradeNo());
                    if("WAIT_BUYER_PAY".equals(status)){
                        alipayService.closeZhiFuBaoTrade(paymentInfo.getTradeNo(),paymentInfo.getOutTradeNo());
                    }
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            log.error("[支付服务]监听到关闭交易记录处理异常,消息:{}",e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
    }
}
